package cn.zmlio.mybatisdbchecker.common;

import lombok.Getter;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

@Getter
public class Result<T> {
    private final T data;
    private final String message;
    private final boolean success;

    private Result(T data, String message, boolean success) {
        this.data = data;
        this.message = message;
        this.success = success;
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(data, "success", true);
    }

    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> failure(String message) {
        return new Result<>(null, message, false);
    }

    public <R> Result<R> map(Function<T, R> mapper) {
        if (success) {
            return Result.success(mapper.apply(data));
        }
        return Result.failure(message);
    }

    public Result<T> onSuccess(Consumer<T> consumer) {
        if (success) {
            consumer.accept(data);
        }
        return this;
    }

    public Result<T> onFailure(Consumer<String> consumer) {
        if (!success) {
            consumer.accept(message);
        }
        return this;
    }

    public Optional<T> toOptional() {
        return success ? Optional.ofNullable(data) : Optional.empty();
    }

    public T orElse(T other) {
        return success ? data : other;
    }

    public T orElseThrow() {
        if (success) {
            return data;
        }
        throw new RuntimeException(message);
    }

    public T orElseThrow(Function<String, ? extends RuntimeException> exceptionSupplier) {
        if (success) {
            return data;
        }
        throw exceptionSupplier.apply(message);
    }
} 